import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar

import 'nprogress/nprogress.css' // progress bar style
import { readToken } from '@/utils/auth' // get token from cookie
import getTitle from '@/utils/getTitle'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  NProgress.start() // start progress bar
  document.title = getTitle(to.meta.title) // set page title
  let hasPermission = true
  const hasToken = readToken()
  const metaRoles = to?.meta?.roles || []
  if (hasToken) {
    const roles = store.getters.roles
    if (metaRoles.length > 0) {
      hasPermission = roles.some(role => metaRoles.includes(role))
    }
    const hasRoles = roles && roles.length > 0 && !roles.includes('blacklist') && hasPermission
    if (roles.length) {
      if (hasRoles || metaRoles.length === 0) {
        next()
      } else {
        next('/index')
      }
    } else {
      try {
        await store.dispatch('user/userInfo')
        next({ ...to, replace: true })
      } catch (error) {
        await store.dispatch('user/resetToken')
        next('/index')
        NProgress.done()
      }
    }
  } else {
    /* has no token*/
    if (metaRoles.length > 0) {
      hasPermission = false
    }
    if (hasPermission) {
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/index')
    }
    NProgress.done()
  }
})
